<?php
define("ROOT", "..");
require_once(ROOT . "/Environment.php");
require_once(LIB . "/layout/Layout.php");
require_once(LIB . "/board/PostRepository.php");

$layout = new Layout("board");

$action = $_GET["action"];
$layout->setAction($action);

$repo = new PostRepository();
switch($action) {
	case "view":
		$idx = $_GET["idx"];
		$post = $repo->load($idx);
		$layout->setProperty("post", $post);
		break;
	case "list":
		$posts = $repo->loadList();
		$layout->setProperty("posts", $posts);
		break;
	case "add":
		$post = new Post();
		$post->subject = $_POST["subject"];
		$post->contents = $_POST["contents"];
		$repo->insert($post);
		
		$posts = $repo->loadList();
		$layout->setProperty("posts", $posts);
		$layout->setAction("list");
		break;
	case "mod":
		$post = new Post();
		$post->idx = $_POST["idx"];
		$post->subject = $_POST["subject"];
		$post->contents = $_POST["contents"];
		$repo->update($post->idx, $post);
		
		$layout->setProperty("post", $post);
		$layout->setAction("view");
		break;
	case "addform":
		$layout->setProperty("form_action", "./?action=add");
		$layout->setProperty("form_name", "새 글 작성");
		$layout->setAction("form");
		break;
	case "modform":
		$idx = $_GET["idx"];
		$post = $repo->load($idx);
		$layout->setProperty("post", $post);
		
		$layout->setProperty("form_action", "./?action=mod");
		$layout->setProperty("form_name", "글 수정");
		$layout->setAction("form");
		break;
	case "del":
		$idx = $_GET["idx"];
		$repo->delete($idx);
		
		$posts = $repo->loadList();
		$layout->setProperty("posts", $posts);
		$layout->setAction("list");
	default:
		break;
}

$layout->view();
?>